<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item>
        <el-button type="success" :icon="Plus" @click="handleAdd">{{ $t('system.globalParam.Add') }}</el-button>
      </el-form-item>
      <el-form-item prop="tenantName">
        <el-input v-model="queryParams.tenantName" :placeholder="$t('system.tenant.name')" clearable
                  @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="refresh">{{ $t('system.globalParam.Search') }}</el-button>
        <el-button :icon="Refresh" @click="resetQuery">{{ $t('system.globalParam.Reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据表格 -->
    <es-table class="es-table" ref="esTable" :dataGetter="handleQuery" @selection-change="handleSelectionChange"
              header-cell-class-name="app-table-head table-head-center"
              :header-cell-style="{background: '#fafafa',color: '#262626', height: '54px' }"
              :row-style="{ height: '68px'}">
      <el-table-column :label="$t('system.tenant.ID')" align="center" prop="tenantId" width="100"/>
      <el-table-column :label="$t('system.tenant.name')" align="center" prop="tenantName"/>
      <el-table-column :label="$t('system.tenant.personC')" align="center" prop="linkman"/>
      <el-table-column :label="$t('system.tenant.numberC')" align="center" prop="contactNumber"/>
      <el-table-column :label="$t('system.tenant.DomainName')" align="center" prop="domain"/>
      <el-table-column :label="$t('system.tenant.Address')" align="center" prop="address"/>
      <el-table-column :label="$t('system.tenant.State')" align="center" prop="status" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :inactive-value="2" :active-value="1"
                     @change="handleStatusChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('source.DataSourceConfiguration.createTime')" align="center" prop="createOn"
                       width="180"/>
      <el-table-column :label="$t('collection.DataCollectionConfiguration.Operation')" align="center" width="200">
        <template #default="scope">
          <!--            <el-button type="success" :icon="Operation" circle plain @click.stop="openRoleResourceDialog(scope.row)"/>-->
          <!--          <el-button type="primary" :icon="Edit" circle plain @click.stop="handleUpdate(scope.row)"/>-->
          <Edit class="operation-icon" color="#409eff" @click.stop="handleUpdate(scope.row)"/>
          <!--          <el-button type="danger" :icon="Delete" circle plain @click.stop="handleDelete(scope.row)"/>-->
          <Delete class="operation-icon" color="#409eff" @click.stop="handleDelete(scope.row)"/>
        </template>
      </el-table-column>
    </es-table>
    <!-- 表单弹窗 -->
    <el-drawer v-model="dialog.visible" :title="dialog.title" size="50%">
      <!--    <el-dialog :close-on-click-modal="false"  :title="dialog.title" v-model="dialog.visible" width="500px" destroy-on-close>-->
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="auto">
        <el-divider content-position="left">{{ $t('system.tenant.TenantInformation') }}</el-divider>
        <el-form-item :label="$t('system.tenant.ID')" prop="tenantId">
          <el-input v-model.trim="formData.tenantId" :placeholder="$t('system.tenant.idE')" length="6"/>
        </el-form-item>
        <el-form-item :label="$t('system.tenant.name')" prop="tenantName">
          <el-input v-model="formData.tenantName" :placeholder="$t('system.tenant.nameEtenant')"/>
        </el-form-item>
        <el-form-item :label="$t('system.tenant.DomainName')" prop="domain">
          <el-input v-model="formData.domain" :placeholder="$t('system.tenant.domainE')"/>
        </el-form-item>
        <el-form-item :label="$t('system.tenant.personC')" prop="linkman">
          <el-input v-model="formData.linkman" :placeholder="$t('system.tenant.contactE')"/>
        </el-form-item>
        <el-form-item :label="$t('system.tenant.numberC')" prop="contactNumber">
          <el-input v-model="formData.contactNumber" :placeholder="$t('system.tenant.numberE')"/>
        </el-form-item>
        <el-form-item :label="$t('system.tenant.Address')" prop="address">
          <el-input v-model="formData.address" :placeholder="$t('system.tenant.addressE')"/>
        </el-form-item>
        <div v-if="dialog.title == $t('system.tenant.tenantAdd')">
          <el-divider content-position="left">{{ $t('system.tenant.information') }}</el-divider>
          <el-form-item :label="$t('system.tenant.nameU')" prop="username">
            <el-input v-model.trim="formData.username" :placeholder="$t('system.tenant.nameEuser')"/>
          </el-form-item>
          <el-form-item :label="$t('source.FormJDBC.Password')" prop="password">
            <el-input v-model.trim="formData.password" type="password" :placeholder="$t('source.FormJDBC.passwordE')"/>
          </el-form-item>
          <el-form-item :label="$t('system.tenant.passwordC')" prop="password2">
            <el-input v-model.trim="formData.password2" type="password" :placeholder="$t('system.tenant.passwordE')"/>
          </el-form-item>
        </div>
        <div v-else>
          <el-divider content-position="left">{{ $t('system.tenant.list') }}</el-divider>
          <el-table header-cell-class-name="app-table-head table-head-center" :data="formData.userList">
            <el-table-column key="id" :label="$t('system.tenant.numberU')" align="center" prop="id"/>
            <el-table-column key="username" :label="$t('system.tenant.nameU')" align="center" prop="username"/>
            <el-table-column :label="$t('system.tenant.nicknameU')" align="center" prop="name"/>
            <el-table-column :label="$t('system.tenant.phone')" align="center" prop="phone" width="120"/>
            <el-table-column :label="$t('gridpannel.shareGridPannelDialog.State')" align="center" prop="status">
              <template #default="scope">
                <span v-if="scope.row.status === 1">{{ $t('gridpannel.shareGridPannelDialog.Normal') }}</span>
                <span v-if="scope.row.status === 2">{{ $t('gridpannel.shareGridPannelDialog.Close') }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('source.DataSourceConfiguration.createTime')" align="center" prop="createOn"
                             width="180"/>
          </el-table>
          <el-button class="mt-4" style="width: 100%" @click="dialog.isAddAdmin = true"
                     v-if="dialog.isAddAdmin === false">
            {{ $t('system.menu.Add') }}
          </el-button>
        </div>
        <el-space :direction="direction" fill wrap :fill-ratio="90" style="width: 100%"
                  v-if="dialog.isAddAdmin === true">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span> {{ $t('system.tenant.administrator') }}</span>
                <Delete class="operation-icon" style="float: right" @click.stop="dialog.isAddAdmin = false"/>
              </div>
            </template>
            <el-form-item :label="$t('system.tenant.nameU')" prop="username">
              <el-input v-model.trim="formData.username" :placeholder="$t('system.tenant.nameEuser')"/>
            </el-form-item>
            <el-form-item :label="$t('source.FormJDBC.Password')" prop="password">
              <el-input v-model.trim="formData.password" :placeholder="$t('system.tenant.passwordE')"/>
            </el-form-item>
            <el-form-item :label="$t('system.tenant.passwordC')" prop="password2">
              <el-input v-model.trim="formData.password2" :placeholder="$t('system.tenant.passwordE')"/>
            </el-form-item>
          </el-card>
        </el-space>
        <el-divider content-position="left">{{ $t('system.tenant.AdministratorInfo') }}</el-divider>
        <el-form-item :label="$t('system.role.coding')">
          <el-input v-model="formData.role.roleCode" readonly="true" :placeholder="$t('system.role.enterRode')"/>
        </el-form-item>
        <el-form-item :label="$t('system.role.descriptionR')" prop="role.roleDesc">
          <el-input v-model="formData.role.roleDesc" :placeholder="$t('system.role.enterDescription')"/>
        </el-form-item>
        <el-form-item :label="$t('system.role.allocation')" prop="role.menuList">
          <el-tree ref="resourceRef" node-key="value" show-checkbox :data="resourceOptions" :default-expand-all="false">
            <template #default="{ data }">
              {{ data.label }}
            </template>
          </el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormData">{{ $t('gridpannel.addGridPannel.Sure') }}</el-button>
          <el-button @click="cancel">{{ $t('gridpannel.addGridPannel.Cancel') }}</el-button>
        </div>
      </template>
      <!--    </el-dialog>-->
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import {reactive, ref, onMounted, toRefs, nextTick, unref} from "vue";
import {Search, Plus, Edit, View, Refresh, Delete,} from "@element-plus/icons-vue";
import {ElForm, ElTree, ElMessage, ElMessageBox} from "element-plus/es";
import EsTable from "@/components/es-table/index.vue";

//API
import {TenantQueryParam, TenantItem, TenantFormData} from "@/types/system/tenant";
import {
  addTenant,
  deleteTenant,
  getTenantDetail,
  listTenantPages,
  updateTenant,
  updateTenantStatus
} from "@/services/system/tenant";
import {listResources} from "@/services/system/menu";
import {Resource} from "@/types/system/menu";
import {useI18n} from 'vue-i18n'

const {t} = useI18n()
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const resourceRef = ref(ElTree);
const direction = ref('vertical')
const esTable = ref()//es-table组件

const validatePassword = (rule, value, callback) => {
  if (value.length < 6) {
    callback(new Error(t('system.tenant.lengthPassword')));
    return;
  }
  if (formData.value.password2 && formData.value.password !== value) {
    callback(new Error(t('system.tenant.notPasswordsmatch')));
  }
  callback();
}
const validateTenantId = (rule, value, callback) => {
  const flag = new RegExp("[`~!@#$^&*()（）=|{}':;,\\[\\].<>《》/?！￥…+_—\\-【】‘；：”“。，、？ ]");
  if (flag.test(value)) {
    callback(new Error(t('system.tenant.charactersSpecial')))
    return;
  }
  if (value.length !== 6) {
    callback(new Error(t('system.tenant.length')))
    return;
  }
  callback()
}

const state = reactive({
  loading: true,
  // 选中ID数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  queryParams: {
    pageNum: 1,
    pageSize: 8,
  } as TenantQueryParam,
  tenantList: [] as TenantItem[],
  total: 0,
  dialog: {
    title: '',
    visible: false,
    isAddAdmin: false,
  },
  formData: {
    role: {
      roleCode: 'administrator',
      roleDesc: '管理员'
    }
  } as TenantFormData,
  rules: {
    tenantId: [{required: true, message: t('system.tenant.tenantID'), trigger: 'blur'},
      {validator: validateTenantId, trigger: 'blur'}],
    tenantName: [{required: true, message: t('system.tenant.tenantName'), trigger: 'blur'}],
    linkman: [{required: true, message: t('system.tenant.contactPlease'), trigger: 'blur'}],
    contactNumber: [{required: true, message: t('system.tenant.contactNumberPlease'), trigger: 'blur'}],
    username: [{required: true, message: t('system.tenant.administratorPlease'), trigger: 'blur'}],
    password: [{
      required: true,
      message: t('system.tenant.passwordEnter'),
      trigger: 'blur'
    }, {validator: validatePassword, trigger: 'blur'}],
    password2: [{
      required: true,
      message: t('system.tenant.passwordEnter'),
      trigger: 'blur'
    }, {validator: validatePassword, trigger: 'blur'}],
    'role.roleDesc': [{required: true, message: t('system.tenant.roleDescription'), trigger: 'blur'}],
    'role.menuList': [{required: true, message: t('system.tenant.selectTenant'), trigger: 'blur'}],
  },
  // 选中的角色
  resourceOptions: [] as Resource[],
});
const {
  loading,
  multiple,
  queryParams,
  tenantList,
  total,
  dialog,
  formData,
  rules,
  resourceDialogVisible,
  checkedRole,
  resourceOptions
} = toRefs(state);

const refresh = () => {
  unref(esTable).reload()
}

/**
 * 资源添加
 */
const onAddItem = () => {
  state.dialog.isAddAdmin = true;
};

function handleAdd() {
  state.dialog = {
    title: '添加租户',
    visible: true,
  };
  // 获取所有的资源
  listResources().then(({data}) => {
    resourceOptions.value = data;
  });
}

function handleUpdate(row: any) {
  state.dialog = {
    title: t('system.tenant.tenantModify'),
    visible: true,
    isAddAdmin: false,
  };
  getTenantDetail(row.id).then(({data}) => {
    state.formData = data;
    // 勾选的菜单回显
    if (data.role.menuList) {
      data.role.menuList.forEach((v) => {
        nextTick(() => {
          resourceRef.value.setChecked(`${v}`, true, false);
        })
      })
    }
  })
  // 获取所有的资源
  listResources().then(({data}) => {
    resourceOptions.value = data;
  });
}

/**
 * 状态修改
 */
function handleStatusChange(row: { [key: string]: any }) {
  const text = row.status === 1 ? t('system.tenant.Enable') : t('system.tenant.Deactivate');
  ElMessageBox.confirm(t('system.tenant.confirm') + text + '' + row.tenantName + t('system.tenant.it'), t('system.tenant.Warning'), {
    confirmButtonText: t('system.tenant.Sure'),
    cancelButtonText: t('system.tenant.Cancel'),
    type: 'warning',
  }).then(() => {
    return updateTenantStatus(row.id, row.status);
  }).then(() => {
    ElMessage.success(text + t('system.tenant.Success'));
  }).catch(() => {
    row.status = row.status === 1 ? 0 : 1;
  });
}

function submitFormData() {
  loading.value = true;
  //菜单
  state.formData.role.menuList = resourceRef.value.getCheckedNodes(false, true).map((node) => node.value);
  //验证
  dataFormRef.value.validate((valid) => {
    if (valid) {
      if (state.formData.id) {
        updateTenant(state.formData.id, state.formData).then(() => {
          ElMessage.success(t('system.tenant.modificationTenant'));
          cancel();
          unref(esTable).reload()
        });
      } else {
        addTenant(state.formData).then(() => {
          ElMessage.success(t('system.tenant.tenantNew'));
          dialog.value.visible = false;
          unref(esTable).reload()
        });
      }
    }
  });
}

/**
 * 删除租户
 */
function handleDelete(row: { [key: string]: any }) {
  ElMessageBox.confirm(t('system.tenant.deletionConfirm') + row.tenantName + t('system.tenant.it'), t('system.tenant.Warning'), {
    confirmButtonText: t('system.tenant.Sure'),
    cancelButtonText: t('system.tenant.Cancel'),
    type: 'warning',
  }).then(function () {
    deleteTenant(row.id).then(() => {
      ElMessage.success(t('system.tenant.deleteS'));
      unref(esTable).reload()
    });
  }).catch(() => ElMessage.info(t('system.tenant.Undeleted')));
}

/**
 * 表格行选中事件
 */
function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
  state.single = selection.length !== 1;
  state.multiple = !selection.length;
}

/**
 * 取消
 */
function cancel() {
  loading.value = false;
  dialog.value.visible = false;
  formData.value.id = undefined;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

/**
 * 查询
 */
function handleQuery(page: any) {
  if (page) {
    state.queryParams.pageNum = page.page;
    state.queryParams.pageSize = page.limit;
  }
  state.loading = true;
  return listTenantPages(state.queryParams).then(({data}) => {
    // state.tenantList = data.records;
    // state.total = data.total;
    state.loading = false;
    return data || {}
  });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  unref(esTable).reload()
}


onMounted(() => {
  unref(esTable).reload()
});
</script>

<style scoped>

</style>
